<script setup lang="ts">
import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import {
  getTopicDetail,
  saveTopic,
  updateTopic,
} from '#/api/iot/product/topic';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

const emit = defineEmits(['success', 'reload']);
const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    formItemClass: 'col-span-2',
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      fieldName: 'id',
      dependencies: {
        show: () => false,
        triggerFields: [''],
      },
      component: 'Input',
    },
    {
      fieldName: 'productId',
      dependencies: {
        show: () => false,
        triggerFields: [''],
      },
      component: 'Input',
    },
    {
      fieldName: 'topic',
      label: 'Topic',
      rules: 'required',
      component: 'Input',
      // eslint-disable-next-line no-template-curly-in-string
      help: 'Topic必须包含/${deviceSn}/占位符',
      dependencies: {
        disabled() {
          return !!isUpdate.value;
        },
        triggerFields: [''],
      },
    },
    {
      fieldName: 'topicDirection',
      label: '操作权限',
      component: 'Select',
      rules: 'required',
      componentProps: {
        options: [
          {
            value: '1',
            label: '设备订阅',
          },
          {
            value: '2',
            label: '设备发布',
          },
        ],
      },
      dependencies: {
        disabled() {
          return !!isUpdate.value;
        },
        triggerFields: [''],
      },
    },
    {
      fieldName: 'topicDesc',
      label: '描述',
      component: 'Textarea',
    },
  ],
  showDefaultActions: false,
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, drawerApi] = useVbenDrawer({
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    drawerApi.drawerLoading(true);

    const { id, productId } = drawerApi.getData() as {
      id?: number | string;
      productId: string;
    };
    isUpdate.value = !!id;
    if (isUpdate.value && id) {
      const record = await getTopicDetail(id);
      await formApi.setValues(record);
    }
    if (productId) {
      await formApi.setValues({ productId });
    }
    await markInitialized();

    drawerApi.drawerLoading(false);
  },
});

async function handleConfirm() {
  try {
    drawerApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = cloneDeep(await formApi.getValues());
    await (isUpdate.value ? updateTopic(data) : saveTopic(data));
    resetInitialized();
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    drawerApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicModal :title="title" class="w-[500px]">
    <BasicForm />
  </BasicModal>
</template>
